package org.example.uhy.repository.impl;

import org.example.uhy.domain.model.coupon.*;
import org.example.uhy.repository.ram.RamStore;
import org.example.uhy.supports.mechanism.IdGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 卡券仓库实现类
 * 注意，这里是 {@link org.springframework.stereotype.Repository}
 */
@Repository
public class CouponRepositoryImpl implements CouponRepository {
    @Autowired
    IdGenerator idGenerator;
    RamStore<CouponId, Coupon> store = new RamStore<>(10, 100);

    @Override
    public Integer countOfOwner(CouponArchiveId archiveId, CouponOwner owner) {
        return store.filter(coupon -> coupon.owner().equals(owner)).size();
    }

    @Override
    public Optional<Coupon> couponOfId(CouponId couponId) {
        return store.get(couponId);
    }

    @Override
    public void add(Coupon coupon) {
        store.put(coupon.couponId(), coupon);
    }

    @Override
    public void save(Coupon coupon) {
        store.put(coupon.couponId(), coupon);
    }

    @Override
    public List<Coupon> scanExpiredCoupons() {
        LocalDateTime now = LocalDateTime.now();
        return store.filter(coupon -> coupon.effectiveTime().getToTime().isBefore(now));
    }

    @Override
    public CouponId nextIdentity() {
        return CouponId.of(idGenerator.nextIdentity());
    }
}
